import { Command } from '../constant';
import { Dispatch } from 'typings';
import { IAllReducerProps } from '../types';
import { getReducerData } from '@/redux/store';
import api from 'api';
import { extraPathsValue } from '@/redux/util';
import Taro from '@tarojs/taro';

export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },
    async loadGameUserInfo() {
      let customer = Taro.getStorageSync('b2b-wechat@login');
      if (customer.user) customer = customer.user;
      try {
        const gameBase = await api.MemberController.getIplandMemberBase();
        if (gameBase.nickName) {
          customer.name = gameBase.nickName;
        }

        if (gameBase.headPortrait) {
          customer.pictureUrl = gameBase.headPortrait;
        }
      } finally {
        action.commonChange('main.customer', customer);
      }
    },
    
    /**
     * 查询用户信息
     * isAquamarineMember-蓝晶会员
     * isCrystalMember-赤晶会员
     */
    async loadUserInfo() {
      let res = await api.customerBaseController.findCustomerBaseInfo();
      action.commonChange('main.isAquamarineMember', res.isAquamarineMember);
      action.commonChange('main.isCrystalMember', res.isCrystalMember);
      Taro.setStorageSync('gameUserInfo', res);

      if (res.isAquamarineMember || res.isCrystalMember) {
        // 如果是会员，领取每日登录奖励
        action.dailyLoginGetCoin('');
      } else {
        // 获取魔力币
        action.getMagicCoin();
      }
    },

    /**
     * 查询用户的已用游戏次数（判断是否是新人-新人导航）
     */
    async loadUserComputedGameTimes() {
      let result = await api.GoldCoinsController.userComputedGameTimes({});
      // if (result.data == 0) {
      //   // 为0，才展示新人引导
      //   action.commonChange('main.showAgree', true);
      // }
      return result.data;
    },

    /**
     * 非会员赠送游戏 （金币雨专属）
     * @returns
     */
    async giveUserNoVipGameTimes() {
      // 编辑参数
      let params = {
        gameType: 0, // 金币雨
      };
      let { data, code, message } = await api.GoldCoinsController.giveGameTimesNoVip(params);
      console.log('action.ts giveUserNoVipGameTimes data', data);
      return data;
    },

    /**
     * 查询游戏是否可玩：0-魔力金币雨，1-魔力抽盲盒，2-魔力赏，3-魔力抓娃娃，4-魔力抽抽卡，5-刮刮乐
     * @param gameType
     * @returns
     */
    async getGameBaseConfig(gameType) {
      let res = await api.iplandBaseController.getGameBaseConfig({ gameType });
      return res;
    },

    /**
     * 获取乐园导航引导数据
     * @returns
     */
    async getNavigationConfig() {
      let res = await api.iplandBaseController.getNavigationData({});
      res.context.map((item) => {
        if (item.gameType == 0) action.commonChange('main.coinRainNavigationText', item.introduction);
        if (item.gameType == 1) action.commonChange('main.choumangheNavigationText', item.introduction);
        if (item.gameType == 2) action.commonChange('main.molishangNavigationText', item.introduction);
        if (item.gameType == 3) action.commonChange('main.zhuawawaNavigationText', item.introduction);
        if (item.gameType == 4) action.commonChange('main.chouchoukaNavigationText', item.introduction);
        if (item.gameType == 5) action.commonChange('main.scratchNavigationText', item.introduction);
      });
      return res;
    },

    /**
     * 会员每日登录，领取魔力币
     * @returns
     */
    async dailyLoginGetCoin(delFlag) {

      let { data, code, message } = await api.iplandBaseController.dailyLoginGetCoin(delFlag);

      let result = data
        ? {
          ...delFlag,
          ...data,
        }
        : {
          ...delFlag,
        };

      // 无信息则弹出开心收下弹框
      if (!result.id) {
        if (Taro.getStorageSync('iplanNotFirstIn')) {
          // 显示领取弹窗
          action.commonChange('main.showMemberLoginDailyModal', true)
        } else {
          // 如果是首次进入先显示导航，导航结束后显示领取弹窗
          action.commonChange('main.dailyGetCoin', true)
        }
      } else {
        action.getMagicCoin();
      }
    },

    /**
     * 获取魔力币数量
     */
    async getMagicCoin() {
      const result = await api.MemberController.getMemberBase();
      action.commonChange('main.money', result.magicCoin);
    },

    /**
     * 获取排行数据
     * @returns
     */
    async getRankList() {
      // 榜单类型：0-魔力值榜单，1-魔力豆榜单
      let { data, code, message } = await api.iplandBaseController.magicValueList({ type: 0 });
      if (code == 'K-000000') {
        action.commonChange('main.showRankModal', true);
        action.commonChange('main.rankData', data);
      } else {
        Taro.showToast({
          title: message,
          icon: 'none',
        });
      }
    },

    /**
     * 获取排行奖品
     * @returns
     */
    async getLeaderboardRewards() {
      let res = await api.iplandBaseController.leaderboardRewards({ type: 0 });
      action.commonChange('main.leaderboardRewards', res.context);
      return res;
    },

    /**
     * 查询任务列表
     */
    async loadTaskItems(payload) {
      action.commonChange('main.response.loadTask', '');
      action.commonChange('main.status.loadingTask', true);

      // 编辑参数
      // let params = {
      //   ...payload,
      //   gameType: GAME_TYPE, // 暂时
      // };
      let { data, code, message } = await api.iplandBaseController.getTaskList()
      // let { data, code, message } = await api.GameTaskController.getTasksByGameType(params);
      console.log('loadTaskItems action data', data);

      let {
        main: { task },
      } = getData();

      action.commonChange('main.task', {
        ...task,
        items: data || [],
        page: {
          ...task.page,
        },
      });
      action.commonChange('main.response.loadTask', code);
      action.commonChange('main.status.loadingTask', false);
    },

    /**
   * 查询任务详情
   */
    async loadTaskDetailById(payload) {
      action.commonChange('main.response.loadTaskDetail', '');
      action.commonChange('main.status.loadingTaskDetail', true);

      // 编辑参数
      let params = {
        ...payload,
      };

      let { data, code, message } = await api.GameTaskController.getTaskDetailById(params);
      console.log('loadTaskItems action data', data);

      let {
        main: { task },
      } = getData();

      action.commonChange('main.task', {
        ...task,
        detail: {
          ...(data || {}),
        },
      });
      action.commonChange('main.response.loadTaskDetail', code);
      action.commonChange('main.status.loadingTaskDetail', false);
    },

    /**
     *  首页道具
     */
    async propCount() {
      action.commonChange('main.isLoadingList', true);
      const res = await Promise.all([
        api.iplandBaseController.getPropCount({ ruleType: 0 }),
        api.iplandBaseController.getPropCount({ ruleType: 1 }),
      ]);
      action.commonChange([{ paths: 'main.moPropList', value: res[0] }]);
      action.commonChange([{ paths: 'main.ouPropList', value: res[1] }]);

    },

    /**
    * 完成任务
    * @param payload
    */
    async computedTask(payload) {
      // 编辑参数
      let params = {
        ...payload,
      };
      let { data, code, message } = await api.GameTaskController.computedTask(params);
    },
  };
  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageIHomeMain'),
  };
}

//create by moon https://github.com/creasy2010/moon
